#include "ThreadPool.h"

struct ThreadPool *ThreadPoolInit(struct EventLoop *mainloop, int threadNum)
{
    //    struct ThreadPool* threadpool = (struct ThreadPool*) malloc(sizeof(struct ThreadPool));
    //    threadpool->index=0;
    //    threadpool->mainloop = mainloop;
    //    threadpool->threadNum = threadNum;
    //    threadpool->isStart = false;
    //    threadpool->workThreads = (struct WorkThread*)(sizeof(struct WorkThread)*threadNum);
    //     // 子线程初始化
    //    return threadpool;
    struct ThreadPool *pool = (struct ThreadPool *)malloc(sizeof(struct ThreadPool));
    pool->index = 0;
    pool->isStart = false;
    pool->mainloop = mainloop;
    pool->threadNum = threadNum;
    pool->workThreads = (struct WorkThread *)malloc(sizeof(struct WorkThread) * pool->threadNum);
    return pool;
}

void ThreadPoolRun(struct ThreadPool *pool)
{
    // Debug("开始创建线程池并运行");
    assert(pool && !pool->isStart);
    if (pool->mainloop->threadId != pthread_self())
    {
        exit(0);
    }
    pool->isStart = true;
    if (pool->threadNum)
    {
        for (int i = 0; i < pool->threadNum; ++i)
        {
            WorkThreadInit(&pool->workThreads[i], i);
            workThreadRun(&pool->workThreads[i]);
        }
    }
}

// 也是由主线程来做的
struct EventLoop *takeWorkEventLoop(struct ThreadPool *pool)
{
    // 判断指针是否为空 或者pool是否已经启动
    assert(pool->isStart);

    // 这句话怎么理解,启动线程池这个线程是不是主线程
    if (pool->mainloop->threadId != pthread_self())
    {
        exit(0);
    }
    // 判断线程池中取出一个子线程，然后取出里面的反应堆实例
    // 这里就证明了，没有其他线程的时候，是用的主线程
    struct EventLoop *evloop = pool->mainloop;

    if (pool->threadNum > 0)
    {
        // 更新index
        evloop = pool->workThreads[pool->index].evloop;
        pool->index++;
        pool->index %= pool->threadNum;
    }
    return evloop;
}
